package com.yaosheng.thread.interview;

/**
 * Created by yaosheng on 2021/7/6.
 * 自旋实现
 */
public class CASView {

    enum ReadyToRun{
        T1,T2;
    }

    static volatile ReadyToRun r = ReadyToRun.T1;   //volatile保证线程之间的可见性

    public static void main(String[] args) {

        char[] aI = "1234567".toCharArray ();
        char[] aC = "ABCDEFG".toCharArray ();

        new Thread( () -> {
            for(char c : aI){
                while(r != ReadyToRun.T1){}   //自旋判断，不满足判断条件的话继续占用cpu
                System.out.println (c);
                r = ReadyToRun.T2;
            }
        },"t1").start ();

        new Thread( () -> {
            for(char c : aC){
                while(r != ReadyToRun.T2){}
                System.out.println (c);
                r = ReadyToRun.T1;
            }
        },"t2").start ();
    }
}
